package com.hx.eaz.domains

import com.hx.eaz.models.CompanyInfo
import org.apache.poi.ss.usermodel.Cell
import org.apache.poi.ss.usermodel.CellType
import org.apache.poi.ss.usermodel.Workbook
import org.slf4j.LoggerFactory
import java.math.BigDecimal

class Parser(){
    private val logger = LoggerFactory.getLogger(Parser::class.java)

    fun companyInfoParseToMap(books: Map<String, Workbook>): Map<String, List<CompanyInfo>> {
        return books.map {
            it.key to companyInfoParse(it.value)
        }.toMap()
    }

    fun companyInfoParse(workBook: Workbook): List<CompanyInfo> {
        val sheet = workBook.getSheetAt(0)
        val first = sheet.firstRowNum
        val last = sheet.lastRowNum
        val ret = arrayListOf<CompanyInfo>()
        for (i in (first + 1)..last) {
            val row = sheet.getRow(i)
            ret.add(
                    CompanyInfo(
                            name = cellToString(row.getCell(2)),
                            country = cellToString(row.getCell(5)),
                            sort = cellToInt(row.getCell(0)),
                            lastSort = cellToInt(row.getCell(1)),
                            inCome = cellToDecimal(row.getCell(3)),
                            profit = cellToDecimal(row.getCell(4)),
                            categoryStr = cellToString(row.getCell(6))
                    )
            )
        }
        return ret
    }

    private fun cellToString(cell: Cell?): String {
        return cellVal(cell) ?: ""
    }

    private fun cellToInt(cell: Cell?): Int {
        val cv = cellVal(cell)
        return try {
            cv?.toBigDecimal()
                    ?.toInt()
                    ?: -1
        } catch (ex: NumberFormatException) {
            logger.warn("could not format number, number is : $cv")
            -1;
        }
    }

    private fun cellToDecimal(cell: Cell?): BigDecimal {
        val cv = cellVal(cell)
        return try {
            cv?.toBigDecimal() ?: BigDecimal(-1)
        } catch (ex: NumberFormatException) {
            logger.warn("could not format number, number is : $cv")
            BigDecimal(-1)
        }
    }

    private fun cellVal(cell: Cell?): String? {
        if (cell == null) {
            return ""
        }
        return when (cell.cellType) {
            CellType.NUMERIC -> cell.numericCellValue.toString()
            CellType.STRING -> cell.stringCellValue
            CellType.BOOLEAN -> cell.booleanCellValue.toString()
            else -> ""
        }
    }
}